const {
	db,
	dbCmd,
	$,
	result_success,
	result_error,
	appletInfoCollection,
	shopieCollection,
	userCollection
} = require('../../common/constants')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let cUser = await userCollection.doc(payload.uid).get()
	cUser = cUser.data[0]
	if(!cUser.app_id){
		return result_success({})
	}
	//获取当前应用
	let appletInfoData = await appletInfoCollection.doc(cUser.app_id).get()
	appletInfoData = appletInfoData.data[0]
	let queryType = params.queryType
	let startDate = params.startDate
	let endDate = params.endDate
	let startDateTime;
	let endDateTime;
	let timezone = 8;
	let calDateTime = timezone * 60 * 60 * 1000;
	if (startDate) {
		if (!endDate) {
			endDate = startDate
		}
		startDate = new Date(startDate + ' 00:00:00');
		endDate = new Date(endDate + ' 23:59:59');
		if (startDate && startDate.toString().indexOf('UTC') > -1) {
			startDateTime = startDate.getTime() - calDateTime;
			endDateTime = endDate.getTime() - calDateTime;
		} else {
			startDateTime = startDate.getTime();
			endDateTime = endDate.getTime();
		}
	} else {
		let cDate = new Date()
		if (cDate && cDate.toString().indexOf('UTC') > -1) {
			cDate.setHours(cDate.getHours() + 8)
		}
		let cYear = cDate.getFullYear();
		let cMonth = cDate.getMonth() + 1;
		let cDay = cDate.getDate();
		startDate = new Date(cYear + "-" + cMonth + "-" + cDay + ' 00:00:00');
		endDate = new Date(cYear + "-" + cMonth + "-" + cDay + ' 23:59:59');
		if (startDate && startDate.toString().indexOf('UTC') > -1) {
			startDateTime = startDate.getTime() - calDateTime;
			endDateTime = endDate.getTime() - calDateTime;
		} else {
			startDateTime = startDate.getTime();
			endDateTime = endDate.getTime();
		}
	}
	let rData = {
		total_money: 0,
		total_count: 0,
		average_money: 0
	}
	if (!startDateTime || !endDateTime) {
		return result_success(rData)
	}


	let queryShopieTotal = {
		app_id: appletInfoData._id,
		shop_id: appletInfoData._id,
		type: 0,
		"cate":"商城订单",
		create_time: dbCmd.gte(startDateTime).and(dbCmd.lte(endDateTime))
	};
	//交易总数
	let shopieCount = await shopieCollection.where(queryShopieTotal).count()
	let total_count = shopieCount.total
	if (total_count) {
		//交易总金额
		let shopieTotal = await shopieCollection.aggregate().match(queryShopieTotal).group({
			_id: '$app_id',
			total: $.sum('$money')
		}).limit(total_count).end();
		let total_money = 0
		if (shopieTotal.data[0] && shopieTotal.data[0].total) {
			total_money = (shopieTotal.data[0].total / 100).toFixed(2)
		}
		//笔均价
		let average_money = (total_money / total_count).toFixed(2)
		rData = {
			total_money: total_money,
			total_count: total_count,
			average_money: average_money
		}

	}
	return result_success(rData)
}